home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / TPTUTR~1.ZIP / PASCAL05.TXT < prev    next >
Text File  |  1996-03-21  |  13KB  |  344 lines

  1.                    Turbo Pascal for DOS Beginning Tutorial
  2.                              by Glenn Grotzinger
  3.                 Part 5 -- Reading and Writing to Text Files.
  4.              All parts copyright 1995-96 (c) by Glenn Grotzinger
  5.  
  6.  
  7. program part4; uses crt;
  8.  
  9.   { This program offers a menu-type system in order to convert a number
  10.     of seconds to hours, minutes, and seconds; and to convert a military
  11.     time to AM/PM time }
  12.  
  13.   var
  14.     choice: integer;
  15.  
  16.   procedure showmenu;
  17.     { This procedure shows the main menu. }
  18.     begin
  19.       writeln('1. Convert a number of seconds to hours, minutes, and',
  20.               ' seconds.');
  21.       writeln('2. Convert a given military time to AM/PM time.');
  22.       writeln('3. Quit the program.');
  23.       writeln;
  24.       writeln('Please enter a choice:');
  25.     end;
  26.  
  27.   procedure convseconds;
  28.      var
  29.        totalseconds: integer;
  30.        hours, minutes, seconds: integer;
  31.        temp: integer;
  32.      begin
  33.        clrscr;
  34.        write('Enter a total number of seconds: ');
  35.        readln(totalseconds);
  36.        writeln;
  37.        temp := totalseconds div 60;
  38.        seconds := totalseconds mod 60;
  39.        hours := temp div 60;
  40.        minutes := temp mod 60;
  41.        writeln;
  42.        writeln(totalseconds, ' seconds is ', hours, ' hours, ', minutes,
  43.               ' minutes, ', seconds, ' seconds.');
  44.        writeln;
  45.        writeln('Press ENTER to continue:');
  46.        readln;
  47.      end;
  48.  
  49.   procedure convmilitary;
  50.     { Version 1.1.  Bug found and e-mailed to me.  It is appreciated. }
  51.     { Involved the reporting of times from 0000 to 0059...Looks to }
  52.     { be fixed now. (wrote this in a very dazed state -- post-surgery)}
  53.  
  54.     var
  55.       hours, minutes: integer;
  56.       meridian: char;
  57.     begin
  58.       clrscr;
  59.       write('Enter a military time''s hours: ');
  60.       readln(hours);
  61.       write('Enter a military time''s minutes: ');
  62.       readln(minutes);
  63.       if hours >= 12 then
  64.         begin
  65.           meridian := 'P';
  66.           hours := hours - 12;
  67.         end
  68.       else
  69.         meridian := 'A';
  70.       if hours = 0 then
  71.          hours := 12;
  72.       writeln;
  73.       write('It is ');
  74.       write(hours);
  75.       write(':');
  76.       if minutes < 10 then
  77.         write('0');
  78.       write(minutes);
  79.       writeln(' ', meridian, 'M.');
  80.       writeln;
  81.       writeln('Press ENTER to continue:');
  82.       readln;
  83.     end;
  84.  
  85.   begin
  86.     choice := 10;
  87.     while choice <> 3 do
  88.       begin
  89.         clrscr;
  90.         showmenu;
  91.         readln(choice);
  92.         case choice of
  93.           1: convseconds;
  94.           2: convmilitary;
  95.         end;
  96.       end;
  97.   end.
  98. OK.  On to new stuff...
  99.  
  100. Addressing Files
  101. ================
  102. To address a file, we use the assign statement.  We use a text variable to
  103. refer to the file, and a string to refer to the actual pathname and filename
  104. of the file.
  105.  
  106. To open a file, we use a reset(<file variable>); statement to read it.
  107.  
  108. To write a new file, we use a rewrite(<file variable>); statement.
  109.  
  110. To close a file after we are done accessing it for read or write, we use
  111. the close(<filevar>).
  112.  
  113. Special Identifiers
  114. ===================
  115. There are functions defined in standard Pascal which aid us in processing
  116. text files.  They are eof(<filevar>) and eoln(<filevar>).  They return
  117. boolean values.  They are signals we can use in loops to aid us in finding
  118. our way in text files.  EOF signals when we are at the end of a file.
  119. EOLN signals when we are at the end of a line of text in a file.
  120.  
  121. NOTE: Keep in mind, we can have as many files defined as we need.  The only
  122. limitation is that we can only have a maximum of the number of files defined
  123. in the FILES= statement of the config.sys of the particular machine we are
  124. on open at any one time.  It is always prudent to close files after you are
  125. done with them.
  126.  
  127.  
  128. Text file concepts and reading/writing to text files
  129. ====================================================
  130. A sample program to illustrate all the items above.  We will be doing a
  131. character by character read on an input file named DATA.TXT using eoln
  132. and eof properly, and uppercasing the output of the file using the
  133. standard upcase function. The output will be written to another output file
  134. named UPCASED.TXT.
  135.  
  136. program tutorial15;
  137.   var
  138.     infile, outfile: text;
  139.     inputchar: char;
  140.   begin
  141.     assign(infile, 'DATA.TXT'); { associate var infile with DATA.TXT }
  142.     reset(infile); { open DATA.TXT for read }
  143.     assign(outfile, 'UPCASED.TXT'); { assoc. var outfile with UPCASED.TXT }
  144.     rewrite(outfile); { open UPCASED.TXT for write }
  145.     while not eof(infile) do { while we're not at the EOF for infile }
  146.       begin
  147.         while not eoln(infile) do { while not EOLN for infile }
  148.           begin
  149.             read(infile, inputchar);
  150.             write(outfile, upcase(inputchar)); { process and output }
  151.           end;
  152.         writeln(outfile);  { when end of line, advance both files down }
  153.         readln(infile);    { one line }
  154.       end;
  155.     close(infile);     { we're done with both of these files.  Close 'em }
  156.     close(outfile);    { time. }
  157.   end.
  158.  
  159. This program is primarily for illustration purposes of all the new concepts
  160. we need to know in order to access files (there is a lot better way out
  161. there of doing it).  As long as we remember what exactly is read and
  162. considered as each type of variable (integer, char, string[limit], etc,
  163. etc), we can read all sorts of data from a text file and write data back
  164. out to a text file.  To illustrate:  If we have the following input file
  165. as on disk...
  166.  
  167. 14 23 34 53 32 Glenn Grotzinger
  168. 23 23 12 33 23 Clinton Sucks!
  169.  
  170. If we perform ONE read from a varied amount of different types from the
  171. first position of the first line, we will see the following:
  172.  
  173.  CHARread: 1
  174.  INTEGERread: 14
  175.  STRING[20]read: 14 23 34 53 32 Glenn
  176.  STRINGread: 14 23 34 53 32 Glenn Grotzinger
  177.  
  178. readln/writeln goes to the next line, whichever references what we are doing
  179. to the text file.
  180.  
  181. We must keep these general rules in mind (I hope you played around with the
  182. read and write commands a lot, that playing will help you A LOT!).
  183.  
  184. Another illustration to see usage of files.  It's the BETTER rewrite of
  185. tutorial15.  We must also keep in mind that to read a text file, EOLN
  186. is not necessarily required, but EOF is ALWAYS REQUIRED.  Improvements:
  187. We can use a string and write a function to uppercase the whole string.
  188. Plus, there's one little logic error above...Figure out why I do the
  189. reads and writes different below and you'll have mastered the idea of
  190. reading/writing files...(I intended to just demo the commands earlier,
  191. this is a demo of how they should be used logically...)
  192.  
  193. program tutorial16;
  194.  
  195.   var
  196.     inputstring: string;
  197.     infile, outfile: string;
  198.  
  199.   function upstr(instring: string):string;
  200.     { This function uppercases a whole string }
  201.     var
  202.       i: integer;
  203.       newstr: string;
  204.     begin
  205.       newstr := '';
  206.       for i := 1 to length(instring) do
  207.         newstr := newstr + upcase(instring[i]);
  208.       { we can piece strings together using +.  Keep it in mind }
  209.     end;
  210.  
  211.    begin
  212.      assign(infile, 'DATA.TXT');
  213.      reset(infile);
  214.      assign(outfile, 'UPCASED.TXT');
  215.      rewrite(outfile);
  216.      readln(infile, inputstring);
  217.      while not eof(infile) do
  218.        begin
  219.          writeln(outfile, upstr(inputstring));
  220.          readln(infile, inputstring);
  221.        end;
  222.      writeln(outfile, upstr(inputstring));
  223.      close(infile);
  224.      close(outfile);
  225.    end.
  226.  
  227. Remember to play with the logic in accessing text files.  And in reading and
  228. writing files, BE SURE YOU USE FILES THAT YOU CAN STAND TO LOSE IF YOU ARE
  229. NOT COMPLETELY COMFORTABLE WITH PROGRAMMING FOR FILE ACCESS.  IF A FILE
  230. BY A NAME YOU USE FOR A PROGRAM ALREADY EXISTS ON THE DRIVE, AND YOU REWRITE
  231. IT, IT WILL BE COMPLETELY LOST!  THIS MEANS ANY UNDELETE PROGRAM WILL *NOT*
  232. BE ABLE TO RECOVER THE FILE!!!!!!!!!!!   I will cover in a later part
  233. how to find out whether files exist on the drive as well as other commands
  234. and functions used in Pascal to perform DOS-like functions (delete files,
  235. make directories, remove directories, and so forth).
  236.  
  237. Printer Output
  238. ==============
  239.         The printer can basically be treated as a write-only file (you only
  240. rewrite it, not reset it).  To use the printer?  Use the unit printer, like
  241. you did the unit crt or wincrt before then write to a text file variable
  242. named lst....Printer defines everything you need to write to the printer.
  243. Printer assumes LPT1, so if your printer is on something else, you can
  244. define the text file variable to be the port address for the printer....
  245.  
  246. program tutorial17; uses printer;
  247.   var
  248.     str: string;
  249.     infile: text;
  250.   begin
  251.     assign(infile, 'PRINTME.TXT');
  252.     reset(infile);
  253.     readln(infile, str);
  254.     while not eof(infile) do
  255.       begin
  256.         writeln(lst, str);
  257.         readln(infile, str);
  258.       end;
  259.     writeln(lst, str);
  260.     writeln('File sent to printer on LPT1..');
  261.   end.
  262.  
  263.  
  264. Practice Programming Problem Notes
  265. ==================================
  266.         Probably ALL programs I pose on these in the future will involve
  267. at least ONE data file off of disk.  If it is a binary one that I have
  268. created for express purpose of these problems, I will be attaching it to
  269. the tutorial message as a binary file attachment.  If its a text file,
  270. I will probably ask you to create it, giving you the format.  If you have
  271. been doing source code, you should be able to use a text file editor.
  272.  
  273. Practice Programming Problem #5
  274. ===============================
  275.         Write a program in Pascal and entirely Pascal which will conduct
  276. a worker-pay recording.  Be sure the program is modular and uses functions
  277. and procedures to the best benefit, as well as efficiently coded (be sure
  278. you are using format codes!).  We will be reading worker names and data
  279. from a file in the current directory with the program named WORKER.TXT.
  280. Format of input and output files will be covered later.  What we will be
  281. doing is figuring out how much to pay each of these employees in our data
  282. file.  Points to keep in mind:
  283.  
  284.    1) Gross pay is hourly rate * hours-worked for hours worked below 40.
  285.    2) 40 hours of time is full-time pay, beyond 40 hours is time and a half.
  286.       Therefore, we must pay them 1/2 more than we normally would at the
  287.       hourly computed rate for any hours above 40 from point 1.
  288.    3) Income Taxes are 15% of computed gross pay (before taxes, etc).
  289.    4) We must indicate all of these deductions by computations in the output.
  290.    5) We may have 1 employee, we may have 10,000.  We need to give the
  291.       user some indication as to what we are doing (all we will see is
  292.       a blank prompt otherwise.) so they won't think our program has hung
  293.       or crashed.  Write a message such as "Processing <employee name>" to
  294.       the screen for each employee.
  295.  
  296. Write a report of what our deductions are from each person's salary, and
  297. what we are paying each employee to a file named PAYOUT.TXT.
  298.  
  299. Format of WORKER.TXT (I recommend you type this in *EXACTLY* and use it)
  300. --------------------
  301. Glenn Grotzinger    44.25  7.34
  302. Joe Schmoe          65.32  4.35
  303. Jim Nabors          40.00  10.01
  304. Sheila Roberts      32.12  6.25
  305. Kathy York          23.21  11.10
  306. --------------------
  307.  
  308. (the area between all the --- is the WORKER.TXT to use.... -- another note:
  309. be sure there aren't any blank lines at the bottom of the file -- those
  310. cause problems...)
  311. First thing on each line is employee name (max of 20 chars).
  312. Second thing is total hours worked.
  313. Third thing is pay rate.
  314.  
  315. Format of PAYOUT.TXT
  316. --------------------
  317.                       The International Widget, Inc.
  318.                        PayOut And Deductions Sheet
  319.  
  320. Employee              Hours  Rate  GrossPay  Overtime  IncomeTax  NetPay
  321. ========================================================================
  322. Glenn Grotzinger      34.25  7.34   345.23     32.34     15.34    305.23
  323. ...
  324.  
  325.  
  326. --------------------
  327. (The numbers should be correct, and the file should appear sort of like
  328. this, but with more entries (equivalent to the number of entries in the
  329. WORKER.TXT file.  This is only a sample illustration.)
  330.  
  331. Note:  In any program, you should always make accounts for changes in the
  332. number of lines of text in an input file.  Use EOF.  Do not use a
  333. defined set loop.  Also, as a tip, to get the output the way you want it
  334. to look, it doesn't hurt to type it out as a sample, so you know how to
  335. space it when you go into the programming part of it.
  336.  
  337. Next Time
  338. =========
  339. We will discuss arrays and their usage.  If there is a difficulty in inter-
  340. preting data files for text files, tell me, and I will probably attach them
  341. as binaries in the future.  Please send all comments, inquiries, etc, etc
  342. to ggrotz@2sprint.net.  P.S.  Sorry this one ain't too fun...Couldn't think
  343. of anything better to get you the practice in using text files...
  344.